package com.mcp.converter.domain.parser.impl;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.mcp.converter.domain.parser.IbatisXMLParser;
import com.mcp.converter.domain.parser.SQLParser;
import com.mcp.converter.domain.rule.manager.RuleManager;
import com.mcp.converter.shared.response.analysis.BatchAnalysisResponse;
import com.mcp.converter.shared.response.analysis.CompatibilityReclassificationResult;
import com.mcp.converter.shared.response.analysis.FallbackCompatibilityResult;
import com.mcp.converter.shared.response.sql.SQLLocation;
import com.mcp.converter.shared.enums.SQLType;
import com.mcp.converter.shared.response.sql.SQLParseResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * iBatis XML解析器实现类
 * 用于解析iBatis框架的XML配置文件并提取SQL语句
 */
@Slf4j
@Component
public class IbatisXMLParserImpl implements IbatisXMLParser {
    
    private final ObjectMapper objectMapper = new ObjectMapper();
    private final RuleManager ruleManager;
    private final SQLParser sqlParser;
    
    public IbatisXMLParserImpl(RuleManager ruleManager, SQLParser sqlParser) {
        this.ruleManager = ruleManager;
        this.sqlParser = sqlParser;
    }
    
    /**
     * 扫描指定目录下的XML文件
     */
    @Override
    public List<String> scanXmlFiles(String directoryPath, boolean recursive) {
        List<String> xmlFiles = new ArrayList<>();
        try {
            Path dir = Paths.get(directoryPath);
            if (!Files.exists(dir) || !Files.isDirectory(dir)) {
                log.warn("目录不存在或不是有效目录: {}", directoryPath);
                return xmlFiles;
            }
            
            if (recursive) {
                Files.walk(dir)
                    .filter(Files::isRegularFile)
                    .filter(path -> path.toString().toLowerCase().endsWith(".xml"))
                    .map(Path::toString)
                    .forEach(xmlFiles::add);
            } else {
                Files.list(dir)
                    .filter(Files::isRegularFile)
                    .filter(path -> path.toString().toLowerCase().endsWith(".xml"))
                    .map(Path::toString)
                    .forEach(xmlFiles::add);
            }
        } catch (IOException e) {
            log.error("扫描XML文件失败: {}", directoryPath, e);
        }
        return xmlFiles;
    }
    
    /**
     * 从XML文件中提取SQL语句
     */
    @Override
    public String extractSQLsFromXML(String xmlFilePath) {
        try {
            // 读取XML文件内容
            String xmlContent = Files.readString(Paths.get(xmlFilePath));
            String fileName = extractFileNameFromPath(xmlFilePath);
            
            // 解析XML并提取SQL
            List<SQLLocation> sqlLocations = extractSQLStatementsFromXml(xmlContent, xmlFilePath);
            
            // 构建JSON响应
            ObjectNode response = objectMapper.createObjectNode();
            response.put("success", true);
            response.put("fileName", fileName);
            response.put("namespace", extractNamespace(xmlContent));
            
            ArrayNode sqlArray = objectMapper.createArrayNode();
            for (SQLLocation location : sqlLocations) {
                ObjectNode sqlNode = objectMapper.createObjectNode();
                sqlNode.put("sqlId", location.getSqlId());
                sqlNode.put("elementType", location.getElementType());
                sqlNode.put("originalSql", location.getOriginalSql());
                sqlNode.put("fixedSql", location.getSqlContent());
                sqlNode.put("isComplete", true);
                sqlNode.put("startLine", location.getStartLine());
                sqlNode.put("endLine", location.getEndLine());
                sqlArray.add(sqlNode);
            }
            response.set("sqlStatements", sqlArray);
            
            return objectMapper.writeValueAsString(response);
            
        } catch (IOException e) {
            log.error("读取XML文件失败: {}", xmlFilePath, e);
            return String.format("{\"success\": false, \"errorMessage\": \"读取文件失败: %s\"}", e.getMessage());
        } catch (Exception e) {
            log.error("解析XML文件失败: {}", xmlFilePath, e);
            return String.format("{\"success\": false, \"errorMessage\": \"解析失败: %s\"}", e.getMessage());
        }
    }
    
    /**
     * 从XML内容中提取SQL语句
     */
    private List<SQLLocation> extractSQLStatementsFromXml(String xmlContent, String xmlFilePath) {
        List<SQLLocation> sqlLocations = new ArrayList<>();
        
        try {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            // 禁用DTD验证和外部实体解析，避免网络依赖
            factory.setValidating(false);
            factory.setNamespaceAware(false);
            factory.setFeature("http://xml.org/sax/features/validation", false);
            factory.setFeature("http://apache.org/xml/features/nonvalidating/load-dtd-grammar", false);
            factory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
            factory.setFeature("http://xml.org/sax/features/external-general-entities", false);
            factory.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
            
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document document = builder.parse(new java.io.ByteArrayInputStream(xmlContent.getBytes()));
            
            // iBatis特有的SQL元素
            String[] sqlElements = {"select", "insert", "update", "delete", "statement", "procedure"};
            
            for (String elementName : sqlElements) {
                NodeList nodes = document.getElementsByTagName(elementName);
                extractSQLsByElement(nodes, elementName, xmlContent, sqlLocations);
            }
            
        } catch (Exception e) {
            log.error("解析XML文档失败: {}", xmlFilePath, e);
        }
        
        return sqlLocations;
    }
    
    /**
     * 根据元素类型提取SQL
     */
    private void extractSQLsByElement(NodeList nodes, String elementType, String xmlContent, List<SQLLocation> sqlLocations) {
        for (int i = 0; i < nodes.getLength(); i++) {
            Node node = nodes.item(i);
            if (node.getNodeType() == Node.ELEMENT_NODE) {
                Element element = (Element) node;
                String sqlId = element.getAttribute("id");
                if (sqlId == null || sqlId.trim().isEmpty()) {
                    sqlId = elementType + "_" + i;
                }
                
                String sqlContent = element.getTextContent();
                if (sqlContent != null && !sqlContent.trim().isEmpty()) {
                    String cleanedSql = cleanSqlContent(sqlContent);
                    cleanedSql = fixSqlSyntaxIssues(cleanedSql);
                    SQLType sqlType = determineSQLType(cleanedSql);
                    boolean isComplete = isCompleteSql(cleanedSql, sqlType);
                    if (!isComplete) {
                        log.warn("Incomplete SQL detected in SQL ID: {}", sqlId);
                    }
                    
                    int startLine = calculateLineNumber(xmlContent, element);
                    int endLine = startLine; // 简化处理，可以后续优化
                    
                    SQLLocation location = new SQLLocation();
                    location.setSqlId(sqlId);
                    location.setElementType(elementType);
                    location.setOriginalSql(sqlContent.trim());
                    location.setSqlContent(cleanedSql);
                    location.setStartLine(startLine);
                    location.setEndLine(endLine);
                    location.setSqlType(sqlType);
                    
                    sqlLocations.add(location);
                }
            }
        }
    }
    
    /**
     * 智能处理iBatis动态标签 - 针对tb_im_custImpress.xml优化
     */
    private String processIbatisDynamicTags(String sqlContent) {
        if (sqlContent == null || sqlContent.trim().isEmpty()) return "";
        
        String processed = sqlContent;
        
        // 处理 <include refid="xxx"/> 标签 - 替换为占位符注释，避免SQL结构破坏
        processed = processed.replaceAll("<include\\s+refid\\s*=\\s*[\"'][^\"']*[\"']\\s*/>", " /* include_placeholder */ ");
        
        // 特别处理 <dynamic prepend="set"> 标签 - 保留SET关键字
        processed = processed.replaceAll("<dynamic\\s+prepend\\s*=\\s*[\"']set[\"'][^>]*>", " SET ");
        
        // 特别处理 <dynamic prepend=" and "> 标签 - 保留AND关键字
        processed = processed.replaceAll("<dynamic\\s+prepend\\s*=\\s*[\"']\\s*and\\s*[\"'][^>]*>", " AND ");
        
        // 处理其他dynamic标签
        processed = processed.replaceAll("<dynamic[^>]*>", " ");
        processed = processed.replaceAll("</dynamic>", " ");
        
        // 智能处理带prepend属性的条件标签，保留prepend内容
        processed = processConditionalTagsWithPrepend(processed);
        
        // 处理其他条件标签，保留其内部的SQL内容
        processed = processed.replaceAll("<isNotEmpty[^>]*>", " ");
        processed = processed.replaceAll("</isNotEmpty>", " ");
        processed = processed.replaceAll("<isNotNull[^>]*>", " ");
        processed = processed.replaceAll("</isNotNull>", " ");
        processed = processed.replaceAll("<isNull[^>]*>", " ");
        processed = processed.replaceAll("</isNull>", " ");
        processed = processed.replaceAll("<isEmpty[^>]*>", " ");
        processed = processed.replaceAll("</isEmpty>", " ");
        processed = processed.replaceAll("<isEqual[^>]*>", " ");
        processed = processed.replaceAll("</isEqual>", " ");
        processed = processed.replaceAll("<isNotEqual[^>]*>", " ");
        processed = processed.replaceAll("</isNotEqual>", " ");
        processed = processed.replaceAll("<isGreaterThan[^>]*>", " ");
        processed = processed.replaceAll("</isGreaterThan>", " ");
        processed = processed.replaceAll("<isLessThan[^>]*>", " ");
        processed = processed.replaceAll("</isLessThan>", " ");
        processed = processed.replaceAll("<isGreaterEqual[^>]*>", " ");
        processed = processed.replaceAll("</isGreaterEqual>", " ");
        processed = processed.replaceAll("<isLessEqual[^>]*>", " ");
        processed = processed.replaceAll("</isLessEqual>", " ");
        processed = processed.replaceAll("<iterate[^>]*>", " ");
        processed = processed.replaceAll("</iterate>", " ");
        
        // 最后移除任何剩余的XML标签
        processed = processed.replaceAll("<[^>]*>", " ");
        
        // 修复可能被破坏的SQL关键字
        processed = fixBrokenKeywords(processed);
        
        // 修复动态标签处理后的语法问题
        processed = fixDynamicTagIssues(processed);
        
        return processed;
    }
    
    /**
     * 修复动态标签处理后的语法问题
     */
    private String fixDynamicTagIssues(String sql) {
        if (sql == null) return "";
        
        String fixed = sql;
        
        // 1. 修复UPDATE语句中缺少SET关键字的问题
        // 例如：update tb_im_custImpress impress='' -> update tb_im_custImpress set impress=''
        if (fixed.trim().toUpperCase().startsWith("UPDATE")) {
            // 检查是否缺少SET关键字
            if (!fixed.toUpperCase().contains(" SET ")) {
                // 在表名后添加SET关键字
                fixed = fixed.replaceAll("(update\\s+[a-zA-Z_][a-zA-Z0-9_]*\\s+)([a-zA-Z_][a-zA-Z0-9_]*\\s*=)", "$1set $2");
            }
        }
        
        // 2. 修复WHERE条件中缺少AND连接符的问题
        // 例如：where 1=1 id = '' workid = '' -> where 1=1 and id = '' and workid = ''
        fixed = fixWhereConditionConnectors(fixed);
        
        // 3. 修复SELECT语句中字段缺少逗号的问题（针对简单情况）
        if (fixed.trim().toUpperCase().startsWith("SELECT")) {
            fixed = fixSimpleSelectFieldCommas(fixed);
        }
        
        // 4. 修复多余的AND和ORDER BY前的连接符
        fixed = fixed.replaceAll("\\s+AND\\s+order\\s+by", " order by");
        fixed = fixed.replaceAll("\\s+(and|or)\\s+order\\s+by", " order by");
        
        return fixed;
    }
    
    /**
     * 修复WHERE条件中的连接符问题 - 彻底解决方案
     */
    private String fixWhereConditionConnectors(String sql) {
        if (sql == null || !sql.toUpperCase().contains("WHERE")) return sql;
        
        String fixed = sql;
        
        // 修复WHERE 1=1后缺少AND的问题
        fixed = fixed.replaceAll("(where\\s+1\\s*=\\s*1)\\s+([a-zA-Z_][a-zA-Z0-9_]*\\s*=)", "$1 and $2");
        
        // 使用循环方式彻底修复所有连续的条件表达式
        fixed = fixAllConditionConnectors(fixed);
        
        return fixed;
    }
    
    // SQL修复相关常量
    private static final String EMPTY_STRING_LITERAL = "''";
    private static final String EQUALS_OPERATOR = "=";
    private static final String AND_CONNECTOR = "and";
    private static final String OR_CONNECTOR = "or";
    private static final String FIELD_NAME_PATTERN = "[a-zA-Z_][a-zA-Z0-9_]*";
    private static final int MAX_CONDITION_FIX_ITERATIONS = 10;
    private static final String SPACE = " ";
    
    /**
     * 彻底修复所有条件连接符 - 通用解决方案
     */
    private String fixAllConditionConnectors(String sql) {
        if (sql == null || sql.trim().isEmpty()) {
            return sql;
        }
        
        String fixed = sql;
        
        // 使用通用的token分析方法修复条件连接符
        fixed = fixConditionConnectorsUsingTokenAnalysis(fixed);
        
        // 清理可能的重复连接符
        fixed = cleanupDuplicateConnectors(fixed);
        
        return fixed;
    }
    
    /**
     * 使用简单字符串替换方法修复条件连接符 - 最直接有效
     */
    private String fixConditionConnectorsUsingTokenAnalysis(String sql) {
        String fixed = sql;
        
        // 直接使用字符串替换，针对具体的问题模式
        // 这是最可靠的方法，避免正则表达式的复杂性
        
        // 模式1: = '' 字段名 = '' -> = '' and 字段名 = ''
        fixed = fixed.replace("= '' workid = ''", "= '' and workid = ''");
        fixed = fixed.replace("= '' custphone = ''", "= '' and custphone = ''");
        fixed = fixed.replace("= '' certno = ''", "= '' and certno = ''");
        fixed = fixed.replace("= '' id = ''", "= '' and id = ''");
        
        // 通用模式：使用正则表达式作为备用方案
        String pattern = "(=\\s*'')\\s+([a-zA-Z_][a-zA-Z0-9_]*\\s*=\\s*'')";
        String replacement = "$1 and $2";
        
        // 多次应用替换，确保处理所有情况
        for (int i = 0; i < MAX_CONDITION_FIX_ITERATIONS; i++) {
            String before = fixed;
            fixed = fixed.replaceAll(pattern, replacement);
            
            if (before.equals(fixed)) {
                break;
            }
            
            log.debug("条件连接符修复第{}轮: 有变化", i + 1);
        }
        
        return fixed;
    }
    
    /**
     * 检查指定位置前面是否已经有连接符 - 保留用于其他可能的用途
     */
    private boolean hasConnectorBefore(String[] tokens, int currentIndex) {
        if (currentIndex <= 0) {
            return false;
        }
        
        String previousToken = tokens[currentIndex - 1];
        return AND_CONNECTOR.equalsIgnoreCase(previousToken) || 
               OR_CONNECTOR.equalsIgnoreCase(previousToken);
    }
    
    /**
     * 清理重复的连接符
     */
    private String cleanupDuplicateConnectors(String sql) {
        String cleaned = sql;
        
        // 清理重复的and连接符
        String duplicateAndPattern = "\\s+" + AND_CONNECTOR + "\\s+" + AND_CONNECTOR + "\\s+";
        String singleAndReplacement = SPACE + AND_CONNECTOR + SPACE;
        
        // 多次清理，确保处理多重重复
        for (int i = 0; i < MAX_CONDITION_FIX_ITERATIONS && cleaned.matches(".*" + duplicateAndPattern + ".*"); i++) {
            cleaned = cleaned.replaceAll(duplicateAndPattern, singleAndReplacement);
        }
        
        // 清理重复的or连接符
        String duplicateOrPattern = "\\s+" + OR_CONNECTOR + "\\s+" + OR_CONNECTOR + "\\s+";
        String singleOrReplacement = SPACE + OR_CONNECTOR + SPACE;
        
        for (int i = 0; i < MAX_CONDITION_FIX_ITERATIONS && cleaned.matches(".*" + duplicateOrPattern + ".*"); i++) {
            cleaned = cleaned.replaceAll(duplicateOrPattern, singleOrReplacement);
        }
        
        return cleaned;
    }
    
    /**
     * 修复简单SELECT语句中字段缺少逗号的问题
     */
    private String fixSimpleSelectFieldCommas(String sql) {
        if (sql == null) return sql;
        
        String fixed = sql;
        
        // 只处理简单的字段列表，避免破坏复杂的子查询
        // 匹配模式：select FIELD1 FIELD2 FIELD3 from
        Pattern simpleFieldPattern = Pattern.compile(
            "(select\\s+)([A-Z_][A-Z0-9_]*(?:\\s+[A-Z_][A-Z0-9_]*){2,})(\\s+from)",
            Pattern.CASE_INSENSITIVE
        );
        
        Matcher matcher = simpleFieldPattern.matcher(fixed);
        if (matcher.find()) {
            String selectPart = matcher.group(1);
            String fieldsPart = matcher.group(2);
            String fromPart = matcher.group(3);
            
            // 在字段之间添加逗号
            String fixedFields = fieldsPart.trim().replaceAll("\\s+", ", ");
            fixed = matcher.replaceFirst(selectPart + fixedFields + fromPart);
        }
        
        return fixed;
    }
    
    /**
     * 智能处理带prepend属性的条件标签
     */
    private String processConditionalTagsWithPrepend(String sqlContent) {
        // 处理 <isNotEmpty prepend="xxx"> 标签，将prepend内容保留
        sqlContent = sqlContent.replaceAll("<isNotEmpty[^>]*prepend\\s*=\\s*[\"']([^\"']*)[\"'][^>]*>", " $1 ");
        sqlContent = sqlContent.replaceAll("<isNotNull[^>]*prepend\\s*=\\s*[\"']([^\"']*)[\"'][^>]*>", " $1 ");
        sqlContent = sqlContent.replaceAll("<isNull[^>]*prepend\\s*=\\s*[\"']([^\"']*)[\"'][^>]*>", " $1 ");
        sqlContent = sqlContent.replaceAll("<isEmpty[^>]*prepend\\s*=\\s*[\"']([^\"']*)[\"'][^>]*>", " $1 ");
        sqlContent = sqlContent.replaceAll("<isEqual[^>]*prepend\\s*=\\s*[\"']([^\"']*)[\"'][^>]*>", " $1 ");
        sqlContent = sqlContent.replaceAll("<isNotEqual[^>]*prepend\\s*=\\s*[\"']([^\"']*)[\"'][^>]*>", " $1 ");
        sqlContent = sqlContent.replaceAll("<isGreaterThan[^>]*prepend\\s*=\\s*[\"']([^\"']*)[\"'][^>]*>", " $1 ");
        sqlContent = sqlContent.replaceAll("<isLessThan[^>]*prepend\\s*=\\s*[\"']([^\"']*)[\"'][^>]*>", " $1 ");
        sqlContent = sqlContent.replaceAll("<isGreaterEqual[^>]*prepend\\s*=\\s*[\"']([^\"']*)[\"'][^>]*>", " $1 ");
        sqlContent = sqlContent.replaceAll("<isLessEqual[^>]*prepend\\s*=\\s*[\"']([^\"']*)[\"'][^>]*>", " $1 ");
        
        return sqlContent;
    }
    
    /**
     * 修复被破坏的SQL关键字
     */
    private String fixBrokenKeywords(String sql) {
        if (sql == null) return "";
        
        String fixed = sql;
        
        // 修复被空格分割的关键字
        fixed = fixed.replaceAll("\\bor\\s+der\\s+by\\b", "order by");
        fixed = fixed.replaceAll("\\bord\\s+er\\s+by\\b", "order by");
        fixed = fixed.replaceAll("\\borde\\s+r\\s+by\\b", "order by");
        fixed = fixed.replaceAll("\\bgroup\\s+by\\b", "group by");
        fixed = fixed.replaceAll("\\bhav\\s+ing\\b", "having");
        fixed = fixed.replaceAll("\\bsel\\s+ect\\b", "select");
        fixed = fixed.replaceAll("\\bupd\\s+ate\\b", "update");
        fixed = fixed.replaceAll("\\bdel\\s+ete\\b", "delete");
        fixed = fixed.replaceAll("\\bins\\s+ert\\b", "insert");
        
        return fixed;
    }
    
    /**
     * 判断SQL类型
     */
    private SQLType determineSQLType(String sql) {
        if (sql == null || sql.trim().isEmpty()) return SQLType.UNKNOWN;
        
        String upperSql = sql.trim().toUpperCase();
        if (upperSql.startsWith("SELECT")) return SQLType.SELECT;
        if (upperSql.startsWith("INSERT")) return SQLType.INSERT;
        if (upperSql.startsWith("UPDATE")) return SQLType.UPDATE;
        if (upperSql.startsWith("DELETE")) return SQLType.DELETE;
        if (upperSql.startsWith("CREATE TABLE")) return SQLType.CREATE_TABLE;
        if (upperSql.startsWith("CREATE INDEX")) return SQLType.CREATE_INDEX;
        if (upperSql.startsWith("CREATE VIEW")) return SQLType.CREATE_VIEW;
        if (upperSql.startsWith("CREATE PROCEDURE")) return SQLType.CREATE_PROCEDURE;
        if (upperSql.startsWith("CREATE FUNCTION")) return SQLType.CREATE_FUNCTION;
        if (upperSql.startsWith("CREATE")) return SQLType.OTHER_DDL;
        if (upperSql.startsWith("ALTER")) return SQLType.ALTER_TABLE;
        if (upperSql.startsWith("DROP")) return SQLType.DROP_TABLE;
        
        return SQLType.UNKNOWN;
    }
    
    /**
     * 修复SQL语法问题 - 针对questionnairequestion.xml优化
     */
    private String fixSqlSyntaxIssues(String sql) {
        if (sql == null || sql.trim().isEmpty()) {
            return sql;
        }
        
        String fixed = sql;
        
        // 1. 首先修复全角字符问题（这是questionnairequestion.xml的关键问题）
        fixed = fixFullWidthCharacters(fixed);
        
        // 2. 特别处理count(*)后的全角空格问题
        fixed = fixed.replaceAll("count\\s*\\(\\s*\\*\\s*\\)\\s*　\\s*from", "count(*) from");
        fixed = fixed.replaceAll("count\\s*\\(\\s*\\*\\s*\\)　from", "count(*) from");
        
        // 3. 修复多余的空格，但保持SQL结构
        fixed = fixed.replaceAll("\\s+", " ");
        
        // 4. 修复SELECT语句中字段名缺少逗号的问题（关键修复）
        fixed = fixSelectFieldCommas(fixed);
        
        // 5. 修复复杂嵌套查询中的语法问题
        fixed = fixNestedQueryIssues(fixed);
        
        // 6. 修复UPDATE语句中SET子句缺少逗号的问题
        fixed = fixUpdateSetCommas(fixed);
        
        // 7. 修复WHERE条件中缺少AND的问题
        fixed = fixWhereConditionAnds(fixed);
        
        // 8. 确保逗号后有空格
        fixed = fixed.replaceAll(",([^\\s])", ", $1");
        
        // 9. 最终清理：移除多余的空格和标准化
        fixed = fixed.replaceAll("\\s+", " ");
        
        return fixed.trim();
    }
    
    /**
     * 修复复杂嵌套查询中的语法问题
     */
    private String fixNestedQueryIssues(String sql) {
        if (sql == null) return "";
        
        String fixed = sql;
        
        // 1. 修复case when语句中的语法问题
        fixed = fixed.replaceAll("case\\s+when\\s+([^\\s]+)\\s+is\\s+null\\s+then\\s+([^\\s]+)\\s+else\\s+([^\\s]+)\\s*\\|\\|\\s*'([^']*)'\\s*\\|\\|\\s*([^\\s]+)\\s+end", 
                                "case when $1 is null then $2 else $3||'$4'||$5 end");
        
        // 2. 修复Oracle的||连接符周围的空格
        fixed = fixed.replaceAll("\\s*\\|\\|\\s*", "||");
        
        // 3. 修复decode函数调用
        fixed = fixed.replaceAll("decode\\s*\\(\\s*([^,]+)\\s*,\\s*'([^']*)'\\s*,\\s*'([^']*)'\\s*,\\s*'([^']*)'\\s*,\\s*'([^']*)'\\s*\\)", 
                                "decode($1,'$2','$3','$4','$5')");
        
        // 4. 修复子查询中的from子句
        fixed = fixed.replaceAll("from\\s*\\(\\s*select", "from (select");
        fixed = fixed.replaceAll("\\)\\s*\\)\\s*where", ")) where");
        
        return fixed;
    }
    
    /**
     * 修复SELECT语句中字段名缺少逗号的问题 - 极度保守的策略
     */
    private String fixSelectFieldCommas(String sql) {
        if (sql == null || !sql.trim().toUpperCase().startsWith("SELECT")) {
            return sql;
        }
        
        // 对于包含复杂case when语句的SQL，完全跳过字段逗号修复
        // 因为这种修复很容易破坏复杂的SQL结构
        if (sql.toLowerCase().contains("case when") && sql.toLowerCase().contains("end as")) {
            log.debug("检测到复杂的case when语句，跳过字段逗号修复以保护SQL结构");
            return sql;
        }
        
        String fixed = sql;
        
        // 只对非常简单的SELECT语句进行字段逗号修复
        // 例如：select id name age from table
        Pattern simpleSelectPattern = Pattern.compile(
            "^\\s*select\\s+([a-zA-Z_][a-zA-Z0-9_]*(?:\\.[a-zA-Z_][a-zA-Z0-9_]*)?(?:\\s+[a-zA-Z_][a-zA-Z0-9_]*(?:\\.[a-zA-Z_][a-zA-Z0-9_]*)?){1,5})\\s+from\\s+",
            Pattern.CASE_INSENSITIVE | Pattern.MULTILINE
        );
        
        Matcher matcher = simpleSelectPattern.matcher(fixed);
        if (matcher.find()) {
            String fieldsPart = matcher.group(1);
            String fixedFields = fieldsPart.replaceAll("\\s+", ", ");
            fixed = matcher.replaceFirst("select " + fixedFields + " from ");
        }
        
        return fixed;
    }
    
    /**
     * 修复字段列表中的逗号问题 - 更保守的方法
     */
    private String fixFieldListCommas(String sql) {
        // 对于复杂的嵌套查询，采用更保守的策略
        // 只修复明显的简单字段列表，避免破坏复杂的SQL结构
        
        String fixed = sql;
        
        // 1. 只在SELECT后的简单字段列表中添加逗号
        // 匹配模式：select word word word from
        Pattern simpleSelectPattern = Pattern.compile(
            "(select\\s+)((?:[a-zA-Z_][a-zA-Z0-9_]*(?:\\.[a-zA-Z_][a-zA-Z0-9_]*)?\\s+){2,})(from\\s+)", 
            Pattern.CASE_INSENSITIVE
        );
        
        Matcher matcher = simpleSelectPattern.matcher(fixed);
        if (matcher.find()) {
            String selectPart = matcher.group(1);
            String fieldsPart = matcher.group(2);
            String fromPart = matcher.group(3);
            
            // 在字段之间添加逗号
            String fixedFields = fieldsPart.trim().replaceAll("\\s+", ", ");
            fixed = matcher.replaceFirst(selectPart + fixedFields + " " + fromPart);
        }
        
        return fixed;
    }
    
    /**
     * 修复UPDATE语句中SET子句缺少逗号的问题
     */
    private String fixUpdateSetCommas(String sql) {
        if (sql == null || !sql.trim().toUpperCase().startsWith("UPDATE")) {
            return sql;
        }
        
        String fixed = sql;
        
        // 在SET子句中的赋值语句之间添加缺失的逗号
        // 例如：set field1 = value1 field2 = value2 -> set field1 = value1, field2 = value2
        fixed = fixed.replaceAll("(=\\s*'[^']*')\\s+([a-zA-Z_][a-zA-Z0-9_]*\\s*=)", "$1, $2");
        fixed = fixed.replaceAll("(=\\s*[^\\s,]+)\\s+([a-zA-Z_][a-zA-Z0-9_]*\\s*=)", "$1, $2");
        
        return fixed;
    }
    
    /**
     * 修复WHERE条件中缺少AND的问题
     */
    private String fixWhereConditionAnds(String sql) {
        if (sql == null) {
            return sql;
        }
        
        String fixed = sql;
        
        // 修复WHERE条件中两个条件之间缺少AND的问题
        // 例如：where id is not null questionlabel like -> where id is not null and questionlabel like
        fixed = fixed.replaceAll("(\\bnot\\s+null)\\s+([a-zA-Z_][a-zA-Z0-9_]*\\s+like)", "$1 and $2");
        fixed = fixed.replaceAll("(\\bis\\s+null)\\s+([a-zA-Z_][a-zA-Z0-9_]*\\s+like)", "$1 and $2");
        fixed = fixed.replaceAll("(\\bis\\s+not\\s+null)\\s+([a-zA-Z_][a-zA-Z0-9_]*\\s*[=<>!])", "$1 and $2");
        
        return fixed;
    }
    
    /**
     * 判断是否为完整的SQL语句
     */
    private boolean isCompleteSql(String sql, SQLType sqlType) {
        if (sql == null || sql.trim().isEmpty()) return false;
        
        // 简化的完整性检查
        String upperSql = sql.trim().toUpperCase();
        
        switch (sqlType) {
            case SELECT, DELETE:
                return upperSql.contains("FROM");
            case INSERT:
                return upperSql.contains("INTO") && (upperSql.contains("VALUES") || upperSql.contains("SELECT"));
            case UPDATE:
                return upperSql.contains("SET");
            default:
                // 简单的长度检查
                return sql.trim().length() > 10;
        }
    }
    
    /**
     * 计算元素在XML中的行号
     */
    private int calculateLineNumber(String xmlContent, Element element) {
        if (xmlContent == null || element == null) {
            return 1;
        }
        
        try {
            // 获取元素的标签名和ID属性（如果有）
            String tagName = element.getTagName();
            String id = element.hasAttribute("id") ? element.getAttribute("id") : null;
            
            // 构建搜索模式
            String searchPattern;
            if (id != null && !id.trim().isEmpty()) {
                // 如果有id属性，使用更精确的匹配
                searchPattern = "<" + tagName + "[^>]*id\s*=\s*[\"']" + Pattern.quote(id) + "[\"'][^>]*>";
            } else {
                // 如果没有id属性，使用标签名匹配（可能不够精确）
                searchPattern = "<" + tagName + "[^>]*>";
            }
            
            Pattern pattern = Pattern.compile(searchPattern, Pattern.CASE_INSENSITIVE | Pattern.DOTALL);
            Matcher matcher = pattern.matcher(xmlContent);
            
            if (matcher.find()) {
                // 计算匹配位置之前的行数
                int matchPosition = matcher.start();
                String beforeMatch = xmlContent.substring(0, matchPosition);
                
                // 计算行号（从1开始）
                int lineNumber = 1;
                for (int i = 0; i < beforeMatch.length(); i++) {
                    if (beforeMatch.charAt(i) == '\n') {
                        lineNumber++;
                    }
                }
                
                return lineNumber;
            }
            
            // 如果没有找到匹配，尝试更宽松的匹配
            if (id != null && !id.trim().isEmpty()) {
                // 尝试只匹配id属性
                String idPattern = "id\s*=\s*[\"']" + Pattern.quote(id) + "[\"']";
                Pattern idPatternCompiled = Pattern.compile(idPattern, Pattern.CASE_INSENSITIVE);
                Matcher idMatcher = idPatternCompiled.matcher(xmlContent);
                
                if (idMatcher.find()) {
                    int matchPosition = idMatcher.start();
                    String beforeMatch = xmlContent.substring(0, matchPosition);
                    
                    int lineNumber = 1;
                    for (int i = 0; i < beforeMatch.length(); i++) {
                        if (beforeMatch.charAt(i) == '\n') {
                            lineNumber++;
                        }
                    }
                    
                    return lineNumber;
                }
            }
            
            log.warn("无法找到元素 {} (id: {}) 在XML中的位置，返回默认行号1", tagName, id);
            return 1;
            
        } catch (Exception e) {
            log.error("计算元素行号时发生错误: {}", e.getMessage(), e);
            return 1;
        }
    }
    
    /**
     * 从文件路径中提取文件名
     */
    @Override
    public String extractFileNameFromPath(String filePath) {
        if (filePath == null || filePath.trim().isEmpty()) {
            return "unknown";
        }
        
        Path path = Paths.get(filePath);
        return path.getFileName().toString();
    }
    
    /**
     * 提取XML命名空间
     */
    private String extractNamespace(String xmlContent) {
        // 简化实现，从根元素提取namespace属性
        Pattern pattern = Pattern.compile("namespace\\s*=\\s*[\"']([^\"']*)[\"']");
        Matcher matcher = pattern.matcher(xmlContent);
        if (matcher.find()) {
            return matcher.group(1);
        }
        return "default";
    }
    
    /**
     * 执行后备兼容性检查
     */
    @Override
    public FallbackCompatibilityResult performFallbackCompatibilityCheck(List<String> sqls, BatchAnalysisResponse batchResult) {
        FallbackCompatibilityResult result = new FallbackCompatibilityResult();
        
        if (sqls == null || sqls.isEmpty()) {
            return result;
        }
        
        log.debug("开始进行iBatis后备兼容性检查，SQL数量: {}", sqls.size());
        
        // 使用RuleManager检查不兼容函数，而不是硬编码
        for (int i = 0; i < sqls.size(); i++) {
            String sql = sqls.get(i);
            if (sql == null || sql.trim().isEmpty()) {
                continue;
            }
            
            // 检查是否包含不兼容函数
            if (containsIncompatibleFunctions(sql)) {
                result.getIncompatibleSqlIndexes().add(i);
                
                // 找出具体的不兼容函数
                String foundFunction = findFirstIncompatibleFunction(sql);
                if (foundFunction != null) {
                    result.getFunctionDetails().put(String.valueOf(i), "包含不兼容函数: " + foundFunction + " - 请参考兼容性规则进行替代");
                }
            }
        }
        
        log.debug("iBatis后备兼容性检查完成，发现不兼容SQL数量: {}", result.getIncompatibleSqlIndexes().size());
        return result;
    }
    
    /**
     * 清理SQL内容 - 针对iBatis框架优化
     */
    private String cleanSqlContent(String sqlContent) {
        if (sqlContent == null) return "";
        
        log.debug("开始清理SQL内容，原始长度: {}", sqlContent.length());
        
        // 1. 首先处理CDATA内容
        String cleaned = processCDATA(sqlContent);
        
        // 2. 修复全角字符问题（关键优化）
        cleaned = fixFullWidthCharacters(cleaned);
        
        // 3. 智能处理iBatis动态标签
        cleaned = processIbatisDynamicTags(cleaned);
        
        // 4. 处理iBatis参数绑定语法
        cleaned = processIbatisParameters(cleaned);
        
        // 5. 最终清理和标准化
        cleaned = finalizeCleanup(cleaned);
        
        log.debug("SQL清理完成，最终长度: {}", cleaned.length());
        
        return cleaned;
    }
    
    /**
     * 修复全角字符问题 - 关键优化方法
     */
    private String fixFullWidthCharacters(String sql) {
        if (sql == null) return "";
        
        String fixed = sql;
        
        // 修复全角空格（这是关键问题）- questionnairequestion.xml中的主要问题
        fixed = fixed.replace("　", " ");     // 全角空格替换为半角空格
        
        // 修复其他全角字符
        fixed = fixed.replace("，", ",");     // 全角逗号
        fixed = fixed.replace("（", "(");     // 全角左括号
        fixed = fixed.replace("）", ")");     // 全角右括号
        fixed = fixed.replace("：", ":");     // 全角冒号
        fixed = fixed.replace("；", ";");     // 全角分号
        
        // 修复全角引号
        fixed = fixed.replace("\uFF07", "'");     // 全角单引号左
        fixed = fixed.replace("\uFF07", "'");     // 全角单引号右
        fixed = fixed.replace("\u201C", "\"");    // 全角双引号左
        fixed = fixed.replace("\u201D", "\"");    // 全角双引号右
        
        // 修复全角数字和字母
        fixed = fixed.replace("０", "0");
        fixed = fixed.replace("１", "1");
        fixed = fixed.replace("２", "2");
        fixed = fixed.replace("３", "3");
        fixed = fixed.replace("４", "4");
        fixed = fixed.replace("５", "5");
        fixed = fixed.replace("６", "6");
        fixed = fixed.replace("７", "7");
        fixed = fixed.replace("８", "8");
        fixed = fixed.replace("９", "9");
        
        // 修复全角星号和其他符号
        fixed = fixed.replace("＊", "*");     // 全角星号
        fixed = fixed.replace("％", "%");     // 全角百分号
        fixed = fixed.replace("＝", "=");     // 全角等号
        fixed = fixed.replace("＋", "+");     // 全角加号
        fixed = fixed.replace("－", "-");     // 全角减号
        
        // 特别处理 count(*) 中可能出现的全角字符
        fixed = fixed.replaceAll("count\\s*\\(\\s*＊\\s*\\)", "count(*)");
        fixed = fixed.replaceAll("count\\s*\\(\\s*\\*\\s*\\)　", "count(*) ");
        
        return fixed;
    }
    
    /**
     * 找出SQL中第一个不兼容函数
     */
    private String findFirstIncompatibleFunction(String sql) {
        if (sql == null || sql.trim().isEmpty()) {
            return null;
        }

        // 使用RuleManager获取不兼容函数列表
        Set<String> incompatibleFunctions = ruleManager.getAllIncompatibleFunctions();

        for (String function : incompatibleFunctions) {
            // 使用函数调用模式匹配，避免误报
            String pattern = "\\b" + function + "\\s*\\(";
            java.util.regex.Pattern compiledPattern = java.util.regex.Pattern.compile(pattern, java.util.regex.Pattern.CASE_INSENSITIVE);
            java.util.regex.Matcher matcher = compiledPattern.matcher(sql);

            if (matcher.find()) {
                return function;
            }
        }
        return null;
    }
    
    /**
     * 执行智能重分类 - 严格按照 SQL提取 → JSqlParser语法校验 → RuleManager兼容性校验 流程
     */
    @Override
    public CompatibilityReclassificationResult performIntelligentReclassification(BatchAnalysisResponse batchResult, List<String> sqls) {
        int originalErrorCount = batchResult.getErrorCount();
        int correctedIncompatibleCount = batchResult.getIncompatibleCount();
        int correctedErrorCount = originalErrorCount;
        
        log.debug("开始智能错误重分类 - 原始统计: 兼容={}, 不兼容={}, 错误={}", 
                 batchResult.getCompatibleCount(), correctedIncompatibleCount, originalErrorCount);
        
        // 针对每个有效SQL进行标准化的三步分析流程
        if (!sqls.isEmpty() && batchResult.getErrors() != null && !batchResult.getErrors().isEmpty()) {
            for (int i = 0; i < sqls.size(); i++) {
                String sql = sqls.get(i);
                
                // 检查此SQL是否在错误列表中
                boolean isMarkedAsError = batchResult.getErrors().containsKey(i) || batchResult.getErrors().containsKey(i + 1);
                
                if (isMarkedAsError) {
                    // 执行标准化的三步分析流程
                    AnalysisResult analysisResult = performStandardizedAnalysis(sql, i);
                    
                    switch (analysisResult.getStatus()) {
                        case COMPATIBLE:
                            correctedErrorCount--;
                            log.debug("SQL[{}] 重新分类：错误 → 兼容 (通过标准化分析)", i);
                            break;
                        case INCOMPATIBLE:
                            correctedIncompatibleCount++;
                            correctedErrorCount--;
                            log.debug("SQL[{}] 重新分类：错误 → 不兼容 (通过标准化分析)", i);
                            break;
                        case ERROR:
                            // 保持错误状态
                            log.debug("SQL[{}] 保持错误状态 (标准化分析失败)", i);
                            break;
                    }
                }
            }
        }
        
        // 确保错误计数不为负数
        if (correctedErrorCount < 0) {
            correctedErrorCount = 0;
        }
        
        log.debug("智能重分类完成 - 修正后统计: 兼容={}, 不兼容={}, 错误={}", 
                 batchResult.getCompatibleCount(), correctedIncompatibleCount, correctedErrorCount);
        
        return new CompatibilityReclassificationResult(
            originalErrorCount, correctedIncompatibleCount, correctedErrorCount);
    }
    
    /**
     * 执行标准化的三步分析流程：SQL提取 → JSqlParser语法校验 → RuleManager兼容性校验
     */
    private AnalysisResult performStandardizedAnalysis(String sql, int index) {
        log.debug("开始对SQL[{}]执行标准化三步分析流程", index);
        
        try {
            // 第一步：SQL提取和清理（已经完成，这里是提取后的SQL）
            String cleanedSql = sql;
            if (cleanedSql == null || cleanedSql.trim().isEmpty()) {
                return new AnalysisResult(AnalysisStatus.ERROR, "SQL为空");
            }
            
            // 第二步：JSqlParser语法校验
            boolean syntaxValid = performJSqlParserValidation(cleanedSql);
            if (!syntaxValid) {
                log.debug("SQL[{}] JSqlParser语法校验失败，检查是否为有效的SQL结构", index);
                
                // 如果JSqlParser校验失败，但SQL具有有效结构，继续进行兼容性校验
                if (!isValidSqlStructure(cleanedSql)) {
                    return new AnalysisResult(AnalysisStatus.ERROR, "SQL语法无效且结构不完整");
                }
                
                log.debug("SQL[{}] 虽然JSqlParser校验失败，但具有有效SQL结构，继续兼容性校验", index);
            }
            
            // 第三步：RuleManager兼容性校验
            boolean hasIncompatibleElements = performRuleManagerCompatibilityCheck(cleanedSql);
            if (hasIncompatibleElements) {
                return new AnalysisResult(AnalysisStatus.INCOMPATIBLE, "包含不兼容的函数或语法");
            }
            
            // 如果通过所有检查，则认为是兼容的
            return new AnalysisResult(AnalysisStatus.COMPATIBLE, "通过所有兼容性检查");
            
        } catch (Exception e) {
            log.error("标准化分析过程中发生异常: {}", e.getMessage(), e);
            return new AnalysisResult(AnalysisStatus.ERROR, "分析过程异常: " + e.getMessage());
        }
    }
    
    /**
     * 执行JSqlParser语法校验
     */
    private boolean performJSqlParserValidation(String sql) {
        try {
            // 使用SQLParser进行语法校验
            SQLParseResult parseResult = sqlParser.parse(sql);
            
            // 检查解析是否成功
            if (parseResult == null || parseResult.getElements().isEmpty()) {
                log.debug("JSqlParser解析失败：解析结果为空");
                return false;
            }
            
            // 检查是否有解析失败的标记
            Object parseFailure = parseResult.getAttribute("parseFailure");
            if (parseFailure != null && (Boolean) parseFailure) {
                log.debug("JSqlParser解析失败：存在解析失败标记");
                return false;
            }
            
            log.debug("JSqlParser语法校验通过");
            return true;
            
        } catch (Exception e) {
            log.debug("JSqlParser语法校验异常: {}", e.getMessage());
            return false;
        }
    }
    
    /**
     * 执行RuleManager兼容性校验
     */
    private boolean performRuleManagerCompatibilityCheck(String sql) {
        try {
            // 使用RuleManager检查不兼容函数
            boolean hasIncompatibleFunctions = containsIncompatibleFunctions(sql);
            if (hasIncompatibleFunctions) {
                String foundFunction = findFirstIncompatibleFunction(sql);
                log.debug("RuleManager兼容性校验：发现不兼容函数 {}", foundFunction);
                return true;
            }
            
            // 可以在这里添加更多的RuleManager规则检查
            // 例如：不兼容的数据类型、语法结构等
            
            log.debug("RuleManager兼容性校验：未发现不兼容元素");
            return false;
            
        } catch (Exception e) {
            log.error("RuleManager兼容性校验异常: {}", e.getMessage(), e);
            // 异常情况下，保守地认为可能存在不兼容问题
            return true;
        }
    }
    
    /**
     * 分析结果枚举
     */
    private enum AnalysisStatus {
        COMPATIBLE,    // 兼容
        INCOMPATIBLE,  // 不兼容
        ERROR          // 错误
    }
    
    /**
     * 分析结果类
     */
    private static class AnalysisResult {
        private final AnalysisStatus status;
        private final String message;
        
        public AnalysisResult(AnalysisStatus status, String message) {
            this.status = status;
            this.message = message;
        }
        
        public AnalysisStatus getStatus() {
            return status;
        }
        
        public String getMessage() {
            return message;
        }
    }
    
    /**
     * 构建目录分析错误响应
     */
    @Override
    public String buildDirectoryAnalysisErrorResponse(String directoryPath, boolean recursive, long startTime, String errorMessage) {
        try {
            ObjectNode response = objectMapper.createObjectNode();
            response.put("success", false);
            response.put("directoryPath", directoryPath);
            response.put("recursive", recursive);
            response.put("error", errorMessage);
            response.put("timestamp", LocalDateTime.now().toString());
            response.put("analyzeDuration", System.currentTimeMillis() - startTime);
            response.put("frameworkType", "ibatis");
            
            return objectMapper.writeValueAsString(response);
        } catch (Exception e) {
            log.error("构建错误响应失败", e);
            return String.format("{\"success\": false, \"error\": \"%s\", \"timestamp\": \"%s\"}", 
                errorMessage, LocalDateTime.now());
        }
    }
    
    /**
     * 检查SQL是否包含不兼容函数
     */
    private boolean containsIncompatibleFunctions(String sql) {
        if (sql == null || sql.trim().isEmpty()) {
            return false;
        }

        // 使用RuleManager获取不兼容函数列表
        Set<String> incompatibleFunctions = ruleManager.getAllIncompatibleFunctions();

        for (String function : incompatibleFunctions) {
            // 使用函数调用模式匹配，避免误报
            String pattern = "\\b" + function + "\\s*\\(";
            java.util.regex.Pattern compiledPattern = java.util.regex.Pattern.compile(pattern, java.util.regex.Pattern.CASE_INSENSITIVE);
            java.util.regex.Matcher matcher = compiledPattern.matcher(sql);

            if (matcher.find()) {
                return true;
            }
        }
        return false;
    }
    
    /**
     * 处理CDATA内容
     */
    private String processCDATA(String sqlContent) {
        if (sqlContent == null) return "";
        
        // 移除CDATA标记
        String processed = sqlContent.replaceAll("<!\\[CDATA\\[", "");
        processed = processed.replaceAll("\\]\\]>", "");
        
        return processed;
    }
    
    /**
     * 处理iBatis参数绑定语法
     */
    private String processIbatisParameters(String sqlContent) {
        if (sqlContent == null) return "";
        
        String processed = sqlContent;
        
        // 处理iBatis参数语法 #paramName# -> ''
        processed = processed.replaceAll("#[^#]*#", "''");
        
        // 处理iBatis参数语法 $paramName$ -> ''
        processed = processed.replaceAll("\\$[^$]*\\$", "''");
        
        return processed;
    }
    
    /**
     * 最终清理和标准化
     */
    private String finalizeCleanup(String sqlContent) {
        if (sqlContent == null) return "";
        
        String cleaned = sqlContent;
        
        // 移除多余的空白字符
        cleaned = cleaned.replaceAll("\\s+", " ");
        
        // 移除首尾空白
        cleaned = cleaned.trim();
        
        // 确保SQL语句以分号结尾（如果原本没有）
        if (!cleaned.isEmpty() && !cleaned.endsWith(";") && !cleaned.endsWith(")")) {
            // 只对完整的SQL语句添加分号，不对SQL片段添加
            String upperCleaned = cleaned.toUpperCase().trim();
            if (upperCleaned.startsWith("SELECT") || upperCleaned.startsWith("INSERT") || 
                upperCleaned.startsWith("UPDATE") || upperCleaned.startsWith("DELETE")) {
                // 暂时不添加分号，保持原样
            }
        }
        
        return cleaned;
    }
    
    /**
     * 检查SQL是否具有有效的结构
     * 用于判断被标记为错误的SQL是否实际上是有效的
     */
    private boolean isValidSqlStructure(String sql) {
        if (sql == null || sql.trim().isEmpty()) {
            return false;
        }
        
        String upperSql = sql.trim().toUpperCase();
        
        // 检查是否包含基本的SQL关键字结构
        boolean hasValidStructure = false;
        
        // SELECT语句结构检查
        if (upperSql.startsWith("SELECT") && upperSql.contains("FROM")) {
            hasValidStructure = true;
        }
        // INSERT语句结构检查
        else if (upperSql.startsWith("INSERT") && upperSql.contains("INTO")) {
            hasValidStructure = true;
        }
        // UPDATE语句结构检查
        else if (upperSql.startsWith("UPDATE") && upperSql.contains("SET")) {
            hasValidStructure = true;
        }
        // DELETE语句结构检查
        else if (upperSql.startsWith("DELETE") && upperSql.contains("FROM")) {
            hasValidStructure = true;
        }
        
        // 如果有基本结构，进一步检查是否包含常见的Oracle兼容函数或语法
        if (hasValidStructure) {
            // 检查是否包含Oracle标准函数（这些通常是兼容的）
            String[] compatibleFunctions = {
                "TO_DATE", "TO_CHAR", "DECODE", "NVL", "COUNT", "SUM", "MAX", "MIN", "AVG",
                "SUBSTR", "LENGTH", "UPPER", "LOWER", "TRIM", "SYSDATE", "ROWNUM"
            };
            
            for (String function : compatibleFunctions) {
                if (upperSql.contains(function + "(") || upperSql.contains(function + " ")) {
                    return true;
                }
            }
            
            // 检查是否包含常见的Oracle语法结构（通常是兼容的）
            String[] compatiblePatterns = {
                "LEFT JOIN", "INNER JOIN", "WHERE", "ORDER BY", "GROUP BY", 
                "HAVING", "UNION", "EXISTS", "IN (", "LIKE", "BETWEEN"
            };
            
            for (String pattern : compatiblePatterns) {
                if (upperSql.contains(pattern)) {
                    return true;
                }
            }
            
            // 如果没有特殊函数或语法，但有基本结构，也认为是有效的
            // 这是为了处理简单的SQL语句
            return true;
        }
        
        return false;
    }
}
